<template>
  <div class="history-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="开单记录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 开单记录内容 -->
    <div class="history-content">
      <!-- 筛选选项 -->
      <div class="filter-section">
        <van-tabs v-model:active="activeStatus" @change="onStatusChange">
          <van-tab title="全部" name="all" />
          <van-tab title="待支付" name="pending" />
          <van-tab title="已支付" name="paid" />
          <van-tab title="已完成" name="completed" />
        </van-tabs>
      </div>

      <!-- 记录列表 -->
      <div class="record-list">
        <!-- 加载状态 -->
        <div v-if="loading && orderRecords.length === 0" class="loading-container">
          <van-loading size="24px" vertical>加载中...</van-loading>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="!loading && filteredRecords.length === 0" class="empty-container">
          <van-empty 
            image="search" 
            :description="getEmptyDescription()"
          >
            <van-button 
              round 
              type="primary" 
              class="bottom-button"
              @click="router.push('/order-application')"
            >
              立即开单
            </van-button>
          </van-empty>
        </div>
        
        <!-- 记录列表 -->
        <div 
          v-for="record in filteredRecords" 
          :key="record.id"
          class="record-item"
        >
          <div class="record-header">
            <div class="record-info-left">
              <div class="record-number">
                <van-icon name="orders-o" size="14" color="#1989fa" />
                <span>{{ record.applicationNumber }}</span>
              </div>
              <div class="record-time">
                <van-icon name="clock-o" size="12" color="#999" />
                <span>{{ formatDate(record.createTime) }}</span>
              </div>
            </div>
            <div class="record-status" :class="getStatusClass(record.status)">
              {{ getStatusText(record.status) }}
            </div>
          </div>
          
          <div class="record-content">
            <div class="hospital-info">
              <van-icon name="location-o" size="14" color="#1989fa" />
              <span>{{ record.hospitalName }}</span>
            </div>
            
            <div class="record-summary">
              <div class="summary-item">
                <span class="label">项目数量：</span>
                <span class="value">{{ record.projectCount }}项</span>
              </div>
              <div class="summary-item">
                <span class="label">总费用：</span>
                <span class="value price">¥{{ record.totalAmount.toFixed(2) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="record-actions">
              <van-button 
                type="default" 
                size="small"
                @click.stop="goToDetail(record)"
              >
                查看详情
              </van-button>
              <van-button 
                v-if="record.status === OrderApplicationStatus.Submitted"
                type="primary" 
                size="small"
                @click.stop="goToPayment(record)"
              >
                去支付
              </van-button>
              <van-button 
                v-else-if="record.status === OrderApplicationStatus.Completed"
                type="primary" 
                size="small"
                @click.stop="viewReport(record)"
              >
                查看报告
              </van-button>
            </div>
        </div>
        
        <!-- 加载更多 -->
        <div v-if="hasMore && !loading" class="load-more">
          <van-button 
            block 
            type="default" 
            @click="loadMore"
          >
            加载更多
          </van-button>
        </div>
        
        <!-- 底部加载状态 -->
        <div v-if="loading && orderRecords.length > 0" class="loading-more">
          <van-loading size="16px">加载中...</van-loading>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <van-popup 
      v-model:show="showDetail" 
      position="bottom" 
      :style="{ height: '70%', maxWidth: '100%' }"
      round
      teleport="body"
    >
      <div class="detail-popup">
        <div class="detail-header">
          <h3>开单详情</h3>
          <van-icon 
            name="cross" 
            size="18" 
            @click="showDetail = false"
            class="close-btn"
          />
        </div>
        
        <div class="detail-content" v-if="selectedRecord">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="info-row">
              <span class="label">开单时间：</span>
              <span>{{ formatDateTime(selectedRecord.createTime) }}</span>
            </div>
            <div class="info-row">
              <span class="label">院区名称：</span>
              <span>{{ selectedRecord.hospitalName }}</span>
            </div>
            <div class="info-row">
              <span class="label">订单状态：</span>
              <span :class="getStatusClass(selectedRecord.status)">
                {{ getStatusText(selectedRecord.status) }}
              </span>
            </div>
          </div>
          
          <!-- 检查项目 -->
          <div class="detail-section">
            <h4>检查项目</h4>
            <div class="project-list">
              <div 
                v-for="project in selectedRecord.projects" 
                :key="project.id"
                class="project-item"
              >
                <div class="project-info">
                  <div class="project-name">{{ project.name }}</div>
                  <div class="project-desc">{{ project.description }}</div>
                </div>
                <div class="project-price">¥{{ project.price }}</div>
              </div>
            </div>
          </div>
          
          <!-- 费用明细 -->
          <div class="detail-section">
            <h4>费用明细</h4>
            <div class="cost-detail">
              <div class="cost-row">
                <span>检查费用：</span>
                <span>¥{{ selectedRecord.totalAmount }}</span>
              </div>
              <div class="cost-row total">
                <span>总计：</span>
                <span class="total-price">¥{{ selectedRecord.totalAmount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { useUserStore } from '@/stores/user'
import apiService, { 
  type OrderApplicationDto, 
  OrderApplicationStatus, 
  type GetOrderApplicationsRequest,
  type PagedResult 
} from '../api/index'

/**
 * 开单记录页面组件
 * 显示用户的历史开单记录，支持查看详情和后续操作
 */

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const activeStatus = ref('all')
const showDetail = ref(false)
const selectedRecord = ref<OrderRecord | null>(null)

/**
 * 开单记录数据接口（基于后端OrderApplicationDto）
 */
interface OrderRecord {
  id: number
  applicationNumber: string
  createTime: string
  hospitalName: string
  hospitalAddress?: string
  projectCount: number
  totalAmount: number
  status: OrderApplicationStatus
  projects: Project[]
}

/**
 * 项目信息接口
 */
interface Project {
  id: number
  name: string
  description: string
  price: number
  category: 'lab' | 'exam'
}

// 开单记录数据
const orderRecords = ref<OrderRecord[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const hasMore = ref(true)

/**
 * 根据状态筛选记录
 */
const filteredRecords = computed(() => {
  if (activeStatus.value === 'all') {
    return orderRecords.value
  }
  
  let statusFilter: OrderApplicationStatus | undefined
  switch (activeStatus.value) {
    case 'pending':
      statusFilter = OrderApplicationStatus.Submitted
      break
    case 'paid':
      statusFilter = OrderApplicationStatus.Paid
      break
    case 'completed':
      statusFilter = OrderApplicationStatus.Completed
      break
    default:
      return orderRecords.value
  }
  
  return orderRecords.value.filter(record => record.status === statusFilter)
})

/**
 * 点击返回按钮
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 切换状态筛选
 * @param status 状态值
 */
const onStatusChange = (status: string) => {
  console.log('切换状态筛选:', status)
  // 重新加载数据
  loadOrderRecords(true)
}

/**
 * 格式化日期显示
 * @param dateString 日期字符串
 */
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

/**
 * 格式化完整日期时间
 * @param dateString 日期字符串
 */
const formatDateTime = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/**
 * 获取状态文本
 * @param status 状态值
 */
const getStatusText = (status: OrderApplicationStatus) => {
  const statusTexts = {
    [OrderApplicationStatus.Draft]: '草稿',
    [OrderApplicationStatus.Submitted]: '待支付',
    [OrderApplicationStatus.Paid]: '已支付',
    [OrderApplicationStatus.Progress]: '进行中',
    [OrderApplicationStatus.Completed]: '已完成',
    [OrderApplicationStatus.Cancelled]: '已取消'
  }
  return statusTexts[status] || '未知状态'
}

/**
 * 获取状态样式类
 * @param status 状态值
 */
const getStatusClass = (status: OrderApplicationStatus) => {
  const statusClasses = {
    [OrderApplicationStatus.Draft]: 'status-draft',
    [OrderApplicationStatus.Submitted]: 'status-pending',
    [OrderApplicationStatus.Paid]: 'status-paid',
    [OrderApplicationStatus.Progress]: 'status-progress',
    [OrderApplicationStatus.Completed]: 'status-completed',
    [OrderApplicationStatus.Cancelled]: 'status-cancelled'
  }
  return statusClasses[status] || ''
}

/**
 * 获取空状态描述
 */
const getEmptyDescription = () => {
  const descriptions: Record<string, string> = {
    all: '暂无开单记录',
    pending: '暂无待支付订单',
    paid: '暂无已支付订单',
    completed: '暂无已完成订单'
  }
  return descriptions[activeStatus.value] || '暂无记录'
}

/**
 * 查看详情（跳转到详情页面）
 * @param record 开单记录
 */
const viewDetail = (record: OrderRecord) => {
  router.push(`/order-detail/${record.id}`)
}

/**
 * 跳转到详情页面
 * @param record 开单记录
 */
const goToDetail = (record: OrderRecord) => {
  router.push(`/order-detail/${record.id}`)
}

/**
 * 跳转到支付页面
 * @param record 记录信息
 */
const goToPayment = async (record: OrderRecord) => {
  try {
    // 显示加载提示
    Toast.loading({
      message: '加载订单详情...',
      forbidClick: true,
      duration: 0
    })

    // 获取开单申请详情，包含项目信息
    const detailResponse = await apiService.getOrderApplicationDetail(record.id)
    
    if (detailResponse.code === 200 && detailResponse.data) {
      const detail = detailResponse.data
      
      // 构造订单数据，跳转到支付页面
      const orderData = {
        items: detail.items?.map(item => ({
          id: item.medicalProjectId,
          name: item.projectName,
          description: item.projectDescription || '检查项目',
          price: item.projectPrice
        })) || [],
        hospital: {
          name: detail.hospitalAreaName,
          address: '医院地址'
        },
        totalAmount: detail.totalAmount,
        orderId: detail.id,
        applicationNumber: detail.applicationNumber,
        userId: detail.userId
      }
      
      Toast.clear()
      
      // 跳转到支付页面
      router.push({
        path: '/order-payment',
        query: {
          orderData: JSON.stringify(orderData)
        }
      })
    } else {
      Toast.clear()
      Toast('获取订单详情失败')
    }
  } catch (error) {
    Toast.clear()
    console.error('获取订单详情失败:', error)
    Toast('网络错误，请重试')
  }
}

/**
 * 查看检查报告
 * @param record 记录信息
 */
const viewReport = (record: OrderRecord) => {
  Toast('检查报告功能开发中...')
}

/**
 * 加载开单记录数据
 * @param reset 是否重置数据
 */
const loadOrderRecords = async (reset: boolean = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    if (reset) {
      currentPage.value = 1
      orderRecords.value = []
    }
    
    // 构建查询参数
    const params: GetOrderApplicationsRequest = {
      userId: userStore.userId, // 使用当前登录用户的ID
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'CreateTime',
      sortAscending: false
    }
    
    // 根据当前筛选状态添加状态过滤
    if (activeStatus.value !== 'all') {
      switch (activeStatus.value) {
        case 'pending':
          params.status = OrderApplicationStatus.Submitted
          break
        case 'paid':
          params.status = OrderApplicationStatus.Paid
          break
        case 'completed':
          params.status = OrderApplicationStatus.Completed
          break
      }
    }
    
    const response = await apiService.getOrderApplications(params)
    
    if (response.code === 200 && response.data) {
      const pagedResult = response.data
      
      // 转换数据格式
      const newRecords: OrderRecord[] = pagedResult.items.map(item => ({
        id: item.id,
        applicationNumber: item.applicationNumber,
        createTime: item.createTime,
        hospitalName: item.hospitalAreaName,
        status: item.status,
        totalAmount: item.totalAmount,
        projectCount: item.projectCount,
        projects: [] // 详情页面会单独加载项目信息
      }))
      
      if (reset) {
        orderRecords.value = newRecords
      } else {
        orderRecords.value.push(...newRecords)
      }
      
      totalCount.value = pagedResult.totalCount
      hasMore.value = currentPage.value < pagedResult.totalPages
      
      console.log('开单记录加载成功:', {
        total: pagedResult.totalCount,
        currentPage: currentPage.value,
        totalPages: pagedResult.totalPages
      })
    } else {
      Toast(response.message || '加载开单记录失败')
    }
  } catch (error) {
    console.error('加载开单记录失败:', error)
    
    // 提供更详细的错误信息
    let errorMessage = '网络错误，请稍后重试'
    if (error instanceof TypeError && error.message.includes('fetch')) {
      errorMessage = '无法连接服务器，请检查网络连接或确保后端服务已启动'
    } else if (error instanceof Error && error.message.includes('HTTP')) {
      errorMessage = `服务器响应异常: ${error.message}`
    }
    
    Toast(errorMessage)
    
    // 开发环境提示
    if (import.meta.env.DEV) {
      console.warn('开发环境提示：')
      console.warn('1. 确保后端服务已启动：')
      console.warn('   - Read API: http://localhost:5030')
      console.warn('   - Write API: http://localhost:5049')
      console.warn('2. 检查防火墙设置')
      console.warn('3. 检查端口是否被占用')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 加载更多数据
 */
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value++
  loadOrderRecords(false)
}

/**
 * 页面挂载时加载数据
 */
onMounted(() => {
  console.log('开单记录页面已加载')
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    Toast('请先登录')
    router.push('/login')
    return
  }
  
  // 确保用户ID有效
  if (userStore.userId <= 0) {
    Toast('用户信息异常，请重新登录')
    router.push('/login')
    return
  }
  
  // 加载开单记录数据
  loadOrderRecords(true)
  
  // 检查是否需要显示订单详情
  const showDetailParam = route.query.showDetail as string
  const orderDetailParam = route.query.orderDetail as string
  
  if (showDetailParam === 'true' && orderDetailParam) {
    try {
      const orderDetail = JSON.parse(orderDetailParam)
      
      // 将新订单添加到记录列表的开头
      const newRecord: OrderRecord = {
        id: orderDetail.orderId,
        applicationNumber: orderDetail.applicationNumber || `ORD${orderDetail.orderId}`,
        createTime: orderDetail.createTime,
        hospitalName: orderDetail.hospitalName,
        status: orderDetail.status === 'paid' ? OrderApplicationStatus.Paid : OrderApplicationStatus.Submitted,
        totalAmount: parseFloat(orderDetail.totalAmount),
        projectCount: orderDetail.projects.length,
        projects: orderDetail.projects
      }
      
      // 添加到记录列表开头
      orderRecords.value.unshift(newRecord)
      
      // 设置选中的记录并显示详情
      selectedRecord.value = newRecord as OrderRecord
      showDetail.value = true
      
      console.log('显示新订单详情:', newRecord)
    } catch (error) {
      console.error('解析订单详情数据失败:', error)
      Toast('订单详情数据格式错误')
    }
  }
})
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.history-content {
  padding-bottom: 20px;
}

.filter-section {
  background: white;
  margin-bottom: 10px;
}

.record-list {
  padding: 0 16px;
}

/* 加载和空状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.load-more {
  padding: 16px;
}

/* 记录项样式 */
.record-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.record-item:active {
  transform: scale(0.98);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.record-info-left {
  flex: 1;
}

.record-number {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.record-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.record-status {
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.status-draft {
  background: #f5f5f5;
  color: #666;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-paid {
  background: #f6ffed;
  color: #52c41a;
}

.status-progress {
  background: #e6f7ff;
  color: #1890ff;
}

.status-completed {
  background: #f0f9ff;
  color: #0ea5e9;
}

.status-cancelled {
  background: #fff2f0;
  color: #ff4d4f;
}

.record-content {
  margin-bottom: 12px;
}

.hospital-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
}

.record-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
  padding: 12px;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.summary-item .label {
  font-size: 13px;
  color: #666;
}

.summary-item .value {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.summary-item .value.price {
  color: #ff6b35;
  font-weight: 600;
  font-size: 16px;
}

.record-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 详情弹窗样式 */
.detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
  position: relative;
}

/* 确保弹窗在手机屏幕内显示 */
:deep(.van-popup) {
  max-width: 100% !important;
  left: 0 !important;
  right: 0 !important;
  margin: 0 auto !important;
  box-sizing: border-box !important;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
  border-bottom: 1px solid #ebedf0;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.detail-content {
  flex: 1;
  padding: 0 20px 20px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .label {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.project-list {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e8e9ea;
}

.project-item:last-child {
  border-bottom: none;
}

.project-info {
  flex: 1;
}

.project-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.project-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.project-price {
  font-size: 14px;
  font-weight: 600;
  color: #ff6b35;
}

.cost-detail {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
}

.cost-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.cost-row.total {
  border-top: 1px solid #e8e9ea;
  margin-top: 8px;
  padding-top: 12px;
  font-weight: 600;
}

.total-price {
  font-size: 16px;
  color: #ff6b35;
}

/* 顶部导航栏样式 */
:deep(.van-nav-bar) {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #ebedf0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-container {
    padding: 0;
  }
  
  .history-content {
    padding: 0 12px;
  }
  
  .filter-section {
    padding: 0;
  }
  
  .record-item {
    margin-bottom: 8px;
    padding: 12px;
  }
  
  .detail-popup {
    padding: 16px;
  }
  
  .detail-header h3 {
    font-size: 16px;
  }
  
  .detail-section h4 {
    font-size: 14px;
  }
}

@media (max-width: 375px) {
  .record-list {
    padding: 8px;
  }
  
  .record-item {
    padding: 12px;
    margin-bottom: 8px;
  }
  
  .hospital-info span {
    font-size: 14px;
  }
  
  .total-amount .amount {
    font-size: 16px;
  }
  
  .detail-header,
  .detail-content {
    padding-left: 16px;
    padding-right: 16px;
  }
}

/* 弹窗内容样式 */
.detail-popup {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  overflow-y: auto;
  background: #fff;
  border-radius: 16px 16px 0 0;
}
</style>